import * as vscode from 'vscode';
import { ViewPanle } from "./provider/panle";
import { getFanyi } from "./provider/api";

export function activate(context: vscode.ExtensionContext) {
	const provider = new ViewPanle(context);

	context.subscriptions.push(vscode.window.registerWebviewViewProvider('fanyizh', provider));
	
	context.subscriptions.push(vscode.commands.registerCommand('fanyiZh.clear',()=>{
		provider.postMessage({type: 'clear'});
	}));

	context.subscriptions.push(vscode.commands.registerCommand('fanyiZh.select',async ()=>{
		const editor = vscode.window.activeTextEditor;
		if(editor) {
			provider.openView();
			const activeDom = editor.document;
			// 获取选中内容
			const selection = editor.selection;
			const { start, end } = selection;
			const text = activeDom.getText(new vscode.Range(start,end)).replace(/[\/|\*]/g, '');
			const data = await getFanyi(text);
			provider.postMessage({ type: 'dsc', data});
		}
	}));
	// 将选中内容翻译为小驼峰变量名
	context.subscriptions.push(vscode.commands.registerCommand('fanyiZh.toVar',async ()=>{
		const editor = vscode.window.activeTextEditor;
		if(editor) {
			const activeDom = editor.document;
			// 获取选中内容
			const selection = editor.selection;
			const { start, end } = selection;
			const position = new vscode.Range(start,end);
			const text = activeDom.getText(position);
			const data = await getFanyi(text);
			if(typeof data === 'string') {
				vscode.window.showInformationMessage(data);
			}else {
				const dst = data[0]?.dst || '';
				let str = '';
				dst.match(/\b\w+\b/g)?.forEach((s,idx)=>{
					if(idx === 0) {
						str += s.replace(/\w/,m=> m.toLowerCase());
					}else {
						str += s.replace(/\w/,m=> m.toUpperCase());
					}
				});
				editor.edit(editBuilder=>{
					editBuilder.replace(position,str);
				});
			}
		}
	}));
}


